import util from "../../../utils/util.js";

var multiArray = null;
var wxTimer1 = null;

const app = getApp();
var dateTimePicker = require('../../../utils/dateTimePicker');
var timer = require('../../../utils/wxTimer.js');
Page({
  data: {
    intervarID: null,
    date: '2018-10-01',
    time: '12:00',
    dateTimeArray: null,
    dateTime: null, //这个是开始时间
    dateTimeArray1: null,
    dateTime1: null, //这个是结束时间
    cChooseId: null, //唯一的课程ID
    cTime: null,
    startYear: 2000,
    endYear: 2050,
    list: [false, false, false, false, false, false],

    sId: null,
    courseName: null,
    // pageBackgroundColor: 
    pageBackgroundColors: ['#E6F3F9', '#E6F3F9'],
    tTodayCourse: null,
    index: 0,
    courseTime: null,
    multiArray: multiArray,
    multiIndex: [0, 0, 0, 0, 0],
    //弹窗相关
    showModalStatus: false,
    animationData: null,
    wxTimerList: {},
    tm: null,
  },
  onShow(e) {
    var that = this;
    that.setData({
      sId: app.globalData.sId,

    })
    if (this.data.sId != null) {
      if (!app.globalData.isStudent) {
        wx.request({
          url: `https://geek-team.xin/schedule/wx_getTeacherScheduleByDay?tId=${app.globalData.sId}`,
          method: 'POST',
          success(res) {
            console.log(res)
            //{{item.cAddress}}{{item.cName}}{{item.tName}}{{item.time}}
            if (res.data != []) {
              that.setData({
                tTodayCourse: res.data
              })
            }
          },
          fail: (res) => console.log("啥玩意三" + res)
        })
      }
    }
  },
  //弹窗动画
  util: function (currentStatu) {
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    this.animation = animation;
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },


  cacel() {
    var that = this
    that.util("close")
    wx.request({
      url: 'https://geek-team.xin/signPeriod/delete',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        course: this.data.cChooseId,
        courseTime: this.data.cTime,
      },
      success: (res) => {
        console.log(res)
        if (res.data == true) {
          wx.showToast({
            title: '取消成功！',
            icon: 'success',
          })
          that.setData({
            wxTimerList: {}

          })
          wxTimer1.stop(that)
        }
        else {
          wx.showToast({
            title: `取消失败${res.data.massage}`,
            image: '/images/error.png',
          })
        }
      },
      fail: (e) => {
        console.log(`${e}`),
          wx.showToast({
            title: `取消失败${e}`,
            image: '/images/error.png',
          })
      }

    })

  },

  powerDrawer: function (statu) {
    var that = this
    that.util(statu)
    // countdown(that);
    wxTimer1 = new timer({
      beginTime: "00:0" + that.data.during + ":59",
      name: 'wxTimer1',
      complete: function () {
        that.util("close")
      }
    })
    wxTimer1.start(that);
  },
  onLoad() {
    this.setData({
      sId: app.globalData.sId
    })
    console.log("onLoad函数 全局sId" + app.globalData.sId);
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj.dateTimeArray.pop();
    var lastTime = obj.dateTime.pop();
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();
    console.log(obj.dateTime)
    this.setData({
      dateTime: obj.dateTime,
      startNum: obj.dateTime[4],
      dateTimeArray: obj.dateTimeArray,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    });
    var that = this;
    this.setData({
      sId: app.globalData.sId,

    })

    if (this.data.sId != null) {

      if (!app.globalData.isStudent) {
        wx.request({
          url: `https://geek-team.xin/schedule/wx_getTeacherScheduleByDay?tId=${app.globalData.sId}`,
          method: 'POST',
          success(res) {
            console.log(res)
            if (res.data != []) {
              that.setData({
                tTodayCourse: res.data
              })
            }
          },
          fail: (res) => console.log("啥玩意三" + res)
        })
      }
    }
    console.log("这是tCourese" + this.data.tTodayCourse);
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    this.setData(data);
  },
  changeDate(e) {
    this.setData({
      date: e.detail.value
    });
  },


  //多节课程view的选中事件
  choseOrNot(e) {
    console.log(e)
    for (var i = 0; i < this.data.list.length; i++) {
      console.log("呵呵1");
      if (i == e.currentTarget.dataset.index) {
        this.data.list[i] = true;
        console.log("呵呵1");
      } else {
        this.data.list[i] = false;
      }
    }
    this.setData({
      courseName: e.currentTarget.dataset.coursename,
      list: this.data.list,
      cChooseId: e.currentTarget.dataset.id,
      cTime: e.currentTarget.dataset.time,
    });
  },
  changeTime(e) {
    this.setData({
      time: e.detail.value
    });
  },
  changeDateTime(e) {
    var that = this
    that.setData({
      dateTime: e.detail.value,
      startNum: e.detail.value[4],
    });
    that.setData({
      during: that.data.endNum - that.data.startNum - 1
    })
  },
  changeDateTime1(e) {
    var that = this
    console.log(e)
    that.setData({
      dateTime1: e.detail.value,
      endNum: e.detail.value[4],
    });
    that.setData({
      during: that.data.endNum - that.data.startNum - 1,

    })
  },
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },
  changeDateTimeColumn1(e) {
    console.log(e)
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },
  postSignTime(e) {
    var that = this;
    if (this.data.dateTime[1] + 1 < 10) {
      var dateTime6 = "0" + (this.data.dateTime[1] + 1)
    } else { //不要问我为什么要写这个，这是个秘密= =
      var dateTime6 = (this.data.dateTime[1] + 1)
    }
    if (this.data.dateTime1[1] + 1 < 10) {
      var dateTime7 = "0" + (this.data.dateTime1[1] + 1)
    } else {
      var dateTime7 = (this.data.dateTime1[1] + 1)
    }
    if ((this.data.dateTime[2] + 1) < 10) {
      var dateTime8 = "0" + (this.data.dateTime[2] + 1)
    } else { //不要问我为什么要写这个，这是个秘密= =
      var dateTime8 = (this.data.dateTime[2] + 1)
    }
    if ((this.data.dateTime1[2] + 1) < 10) {
      var dateTime9 = "0" + (this.data.dateTime1[2] + 1)
    } else {
      var dateTime9 = (this.data.dateTime1[2] + 1)
    }
    if (this.data.dateTime[3] < 10) {
      var dateTime0 = "0" + this.data.dateTime[3]
    } else { //不要问我为什么要写这个，这是个秘密= =
      var dateTime0 = this.data.dateTime[3]
    }
    if (this.data.dateTime1[3] < 10) {
      var dateTime_ = "0" + this.data.dateTime1[3]
    } else {
      var dateTime_ = this.data.dateTime1[3]
    }
    if (this.data.dateTime[4] < 10) {
      var dateTime4 = "0" + this.data.dateTime[4]
    } else { //不要问我为什么要写这个，这是个秘密= =
      var dateTime4 = this.data.dateTime[4]
    }
    if (this.data.dateTime1[4] < 10) {
      var dateTime5 = "0" + this.data.dateTime1[4]
    } else {
      var dateTime5 = this.data.dateTime1[4]
    }
    var startTime = "20" + this.data.dateTime[0] + "-" + dateTime6 + "-" + dateTime8 + " " + dateTime0 + ":" + dateTime4 + ":00"
    var endTime = "20" + this.data.dateTime1[0] + "-" + dateTime7 + "-" + dateTime9 + " " + dateTime_ + ":" + dateTime5 + ":00"
    console.log("这是上传签到信息所需要的信息" + "::" + this.data.cChooseId + "::" + this.data.cTime + startTime + "::" + endTime);

    wx.request({
      url: 'https://geek-team.xin/signPeriod/set',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        course: this.data.cChooseId,
        courseTime: this.data.cTime,
        startTime: startTime,
        endTime: endTime
      },
      success: (res) => {
        console.log(res)
        if (res.data == true) {
          wx.getLocation({
            type: 'gcj02',
            altitude: true,
            success: function (res) {
              var latitude = res.latitude;
              var longitude = res.longitude;
              sendOffLineMessage(that, startTime, endTime, latitude, longitude);
              console.log(latitude + ',' + longitude)
              app.globalData.socket.emit("setSignPeriod",
                `{"course":"${that.data.cChooseId}","courseTime":"${that.data.cTime}","startTime":"${startTime}","endTime":"${endTime}",
          "latitude":"${latitude}","longitude":"${longitude}"}`, (d) => console.log(d))
              wx.showToast({
                title: '提交成功！',
                icon: 'success',
              })
              that.powerDrawer("open")
            }
          })
        } else {
          wx.showToast({
            title: `提交失败${res.data.massage}`,
            image: '/images/error.png',
          })
        }
      },
      fail: (e) => {
        console.log(`${e}`),
          wx.showToast({
            title: `提交失败${e}`,
            image: '/images/error.png',
          })
      }
    })
  },
})

function sendOffLineMessage(that, startTime, endTime, latitude, longitude) {
  wx.request({
    url: 'https://geek-team.xin/offlineMessage/set',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      course: that.data.cChooseId,
      courseTime: that.data.cTime,
      startTime: startTime,
      endTime: endTime,
      latitude: latitude,
      longitude: longitude,
    },
    success: (res) => {
      console.log('sendOffLineMessage' + res);
    }
  });
}

//外部JS引入--》关于日期的
function withData(param) {
  return param < 10 ? '0' + param : '' + param;
}

function getLoopArray(start, end) {
  var start = start || 0;
  var end = end || 1;
  var array = [];
  for (var i = start; i <= end; i++) {
    array.push(withData(i));
  }
  return array;
}

function getMonthDay(year, month) {
  var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0),
    array = null;
  switch (month) {
    case '01':
    case '03':
    case '05':
    case '07':
    case '08':
    case '10':
    case '12':
      array = getLoopArray(1, 31)
      break;
    case '04':
    case '06':
    case '09':
    case '11':
      array = getLoopArray(1, 30)
      break;
    case '02':
      array = flag ? getLoopArray(1, 29) : getLoopArray(1, 28)
      break;
    default:
      array = '月份格式不正确，请重新输入！'
  }
  return array;
}

function getNewDateArry() {
  // 当前时间的处理
  var newDate = new Date();
  var year = withData(newDate.getFullYear()),
    mont = withData(newDate.getMonth() + 1),
    date = withData(newDate.getDate()),
    hour = withData(newDate.getHours()),
    minu = withData(newDate.getMinutes()),
    seco = withData(newDate.getSeconds());

  return [year, mont, date, hour, minu, seco];
}

function dateTimePicker(startYear, endYear, date) {
  // 返回默认显示的数组和联动数组的声明
  var dateTime = [],
    dateTimeArray = [
      [],
      [],
      [],
      [],
      [],
      []
    ];
  var start = startYear || 1978;
  var end = endYear || 2100;
  // 默认开始显示数据
  var defaultDate = date ? [...date.split(' ')[0].split('-'), ...date.split(' ')[1].split(':')] : getNewDateArry();
  // 处理联动列表数据
  /*年月日 时分秒*/
  dateTimeArray[0] = getLoopArray(start, end);
  dateTimeArray[1] = getLoopArray(1, 12);
  dateTimeArray[2] = getMonthDay(defaultDate[0], defaultDate[1]);
  dateTimeArray[3] = getLoopArray(0, 23);
  dateTimeArray[4] = getLoopArray(0, 59);
  dateTimeArray[5] = getLoopArray(0, 59);

  dateTimeArray.forEach((current, index) => {
    dateTime.push(current.indexOf(defaultDate[index]));
  });
  return {
    dateTimeArray: dateTimeArray,
    dateTime: dateTime
  }
}

